package com.wengyingjian.https;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by hzwengyingjian on 17/2/20.
 */
public class TestTbCookieAlive {

    static String loginCookie = "miid=607004444288620662; uss=BxeCjaLG%2B8%2Bi8fr%2FVB%2FwsNjE5WulOdmzBqhwSPAIrNjAv3d4hzLu1EaD980%3D; hng=CN%7Czh-cn%7CCNY; thw=cn; v=0; cna=vT8DEV9fBn0CAXJxxYPndJaI; _tb_token_=eee31fe57ed3b; _umdata=0823A424438F76AB09665CC0588377B5D3600910B699A14574A872ACA37D32E614C496F24F449463CD43AD3E795C914CCD51516E3F07FA6CD5F0EDD3A0899EF8; l=AiMjRbUA6bavo5/X1oW3GTHqM23NHrda; isg=Arm5VO03xQPfRJm5wIO5CcgeyCPyQ614Y1NCOdvuM-BfYtn0Ixa9SCewktFu; uc1=cookie14=UoW%2FWvdDG2A%2F2A%3D%3D&lng=zh_CN&cookie16=URm48syIJ1yk0MX2J7mAAEhTuw%3D%3D&existShop=true&cookie21=Vq8l%2BKCLiv0MyZ1zjQnMQw%3D%3D&tag=7&cookie15=WqG3DMC9VAQiUQ%3D%3D&pas=0; uc3=sg2=BxpRSReStIeCmWep1j1R677YRtWK6FNc0SWEmUKfmG4%3D&nk2=EqefhWnclW8Zvw%3D%3D&id2=UoCLEaUbCeipTw%3D%3D&vt3=F8dARVfSdjXTb3Zd2RY%3D&lg2=UIHiLt3xD8xYTw%3D%3D; existShop=MTQ4NzY1NzAwNg%3D%3D; lid=q291611265; lgc=q291611265; tracknick=q291611265; cookie2=3c8c5e50ab4375bd3be26453bcd7ce4d; sg=595; mt=np=&ci=1_1&cyk=-1_-1; cookie1=VAn%2BSrhUnehPiB3itMA4s%2FOhFo62QHTUdtDDiK%2BaJB4%3D; unb=1126400639; skt=03c9f32bfa1aa2a8; t=e7e53a3daff516f5c20baebac84ec5a8; _cc_=W5iHLLyFfA%3D%3D; tg=0; _l_g_=Ug%3D%3D; _nk_=q291611265; cookie17=UoCLEaUbCeipTw%3D%3D; lc=Vy%2BbZaOBd8jEBuKcWy5F";

    private String signAccount = "78ddbd8eafb74d4573fbbac5677bfa45";

    private String target = "687474703A2F2F7777772E616C696D616D612E636F6D2F696E6465782E68746D";

    public static final String LOGIN_TEST = "http://pub.alimama.com/common/getUnionPubContextInfo.json";

    public static final String KEEP_COOKIE_ALIVE = "https://login.taobao.com/aso/tgs?domain=alimama&sign_account=%s&service=user_on_taobao&target=%s";

    private String runCookie = "t=d97004aaece56a47815163c2b7f6d0ce; cna=vT8DEV9fBn0CAXJxxYPndJaI; _umdata=0823A424438F76AB09665CC0588377B5D3600910B699A14574A872ACA37D32E614C496F24F449463CD43AD3E795C914C3C554F4812F55479E7FFBC6EF1744554; cookie2=a0a53bca67a29b08804b4e34f5c984c5; v=0; _tb_token_=CZZCYHpEDMq; l=AujoRUqEsBCT2KTmwTw8eNExONz6OUwb; isg=AmBg34AQLAhB4ZAiBhj1KVMlMWhqz0QzEqQLAtpxBHsO1QH_gnmuwyqnG8ov; cookie32=2838e07878664d840f8248708704b89a; cookie31=MTE1OTkyNjUxLHEyOTE2MTEyNjUsd2VuZ3lpbmdqaWFuQGZveG1haWwuY29tLFRC; alimamapwag=TW96aWxsYS81LjAgKE1hY2ludG9zaDsgSW50ZWwgTWFjIE9TIFggMTBfMTFfNikgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzU2LjAuMjkyNC44NyBTYWZhcmkvNTM3LjM2; login=WqG3DMC9VAQiUQ%3D%3D; alimamapw=FFYOAldSAAMGU2xWAwcAVwAHUlRVBlZaA1JWVgZVAVAHA1AHVAIDAgUGUw%3D%3D";

    public static void main(String[] args) throws Exception {
        new TestTbCookieAlive().test();
    }

    public void test() throws Exception {
        while (true) {
            try {
                String url = String.format(KEEP_COOKIE_ALIVE, signAccount, target);
                if (!get(url, loginCookie)) {
                    System.out.println(
                            "cookie expire at " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                }
                String resp = HttpUtils.get(LOGIN_TEST, runCookie);
                if (resp.contains("q291611265")) {
                    System.out.println(
                            "test success..." + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                } else {
                    System.out.println("test failed..." + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
                            + ", resp=" + resp);
                }
                Thread.sleep(10L * 60 * 1000);
            } catch (Exception e) {
            }
        }
    }

    private boolean get(String requestUrl, String cookie) throws Exception {
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        URL url = new URL(requestUrl);
        HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
        httpUrlConn.setRequestProperty("Cookie", cookie);
        httpUrlConn.setSSLSocketFactory(ssf);
        String location = httpUrlConn.getHeaderField("Location");
        if ("http://www.alimama.com/index.htm".equals(location)) {
            return true;
        } else {
            System.out.println("location:" + location);
            // BufferedReader br = new BufferedReader(new InputStreamReader(httpUrlConn.getInputStream()));
            // StringBuffer sb = new StringBuffer();
            // String line = br.readLine();
            // while (line != null) {
            // sb.append(line);
            // line = br.readLine();
            // }
            // System.out.println("content:"+sb.toString());
            return false;
        }
    }

    private TrustManager[] tm = { new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    } };
}
